import http from "@/http"

interface IRestService {
    (modelName: string, data?: object): IRestApiService
}
interface IRestApiService {
    add: IRestApi
    del: IRestApi
    update: IRestApi
    replace: IRestApi
    get: IRestApi
    getList: IRestApi
    getFileTree: IRestApi
    getCount: IRestApi
}
interface IRestApi {
    (url?: string, data?: object): Promise<any>
}

// 访问示例：http://localhost:3000/api/rest/user/add
// rest通用接口
export const restService: IRestService = (modelName, data): IRestApiService => {
    const apis: IRestApiService = {
        add: (url, data) => http.post(url, data),
        del: (url, data) => http.delete(url, data),
        update: (url, data) => http.patch(url, data),
        replace: (url, data) => http.put(url, data),
        get: (url, data) => http.get(url, data),
        getList: (url, data) => http.get(url, data),
        getFileTree: (url, data) => http.get(url, data),
        getCount: (url, data) => http.get(url, data),
    }

    // 为每个函数添加柯里化函数
    for (let name in apis) {
        if (apis.hasOwnProperty(name)) {
            apis[name] = curry(apis[name], name).bind(this, modelName, data)
        }
    }
    return apis
}

function curry(fn: Function, fnName: string) {
    return function (...args: [modelName: string, data: object]) {
        const URL = `/rest/${args[0]}/${fnName}`
        args.shift()
        args.unshift(URL)
        console.log(`Call ${fnName} with request address: ${URL}`)
        return fn.apply(this, args)
    }
}
